package string_tool

import (
	"encoding/hex"
	"net/url"
	"strings"
	"time"

	"github.com/google/uuid"
	"github.com/sirupsen/logrus"
	"github.com/u2takey/go-utils/rand"
)

// RemoveRepeatedElement 删除切片重复元素
func RemoveRepeatedElement(arr []string) (newArr []string) {
	keys := make(map[string]bool)
	list := []string{}

	for _, entry := range arr {
		if _, value := keys[entry]; !value {
			keys[entry] = true
			list = append(list, entry)
		}
	}

	return list
}

// GenerateSerialNumber 随机生成字母
func GenerateSerialNumber(size int) string {
	array := []string{"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z",
		"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"}
	u, _ := uuid.NewRandom()
	str := strings.Replace(u.String(), "-", "", -1)
	var serialNumber strings.Builder
	for i := 0; i < size; i++ {
		hexStr, _ := hex.DecodeString(str[i*2 : i*2+2])
		serialNumber.WriteString(array[int(hexStr[0])%len(array)])
	}
	return serialNumber.String()
}

// RandomString 随机字符串
func RandomString(length int) string {
	rand.Seed(time.Now().UnixNano())
	result := make([]rune, length)
	for i := 0; i < length; i++ {
		result[i] = rune('a' + rand.Intn(52)/26*('A'-'a') + rand.Intn(26))
	}
	return string(result)
}

// ReplaceOrConcatDomain 替换或拼接域名
func ReplaceOrConcatDomain(urlStr string, configDomain string) string {
	u, err := url.Parse(urlStr)
	if err != nil {
		logrus.Errorf("Invalid URL: %s", urlStr)
		return ""
	}

	// URL 没有域名，直接拼接配置域名
	configURL, _ := url.Parse(configDomain)
	if configURL.Scheme == "" {
		// 如果配置域名没有协议头，默认使用 http 协议
		configURL.Scheme = "http"
	}

	if u.Path != "" && strings.HasPrefix(u.Path, "/") {
		u.Path = strings.TrimPrefix(u.Path, "/")
	}

	if configDomain != "" && strings.HasSuffix(configDomain, "/") {
		configDomain = strings.TrimSuffix(configDomain, "/")
	}

	return configDomain + "/" + u.Path + "?" + u.RawQuery
}

// GetRelativePath 获取相对路径
func GetRelativePath(urlStr, domain, param string) string {
	u, err := url.Parse(urlStr)
	if err != nil {
		logrus.Errorf("Invalid URL: %s", urlStr)
		return ""
	}

	var relativePath string

	if domain == "" {
		relativePath = u.Path + "?" + u.RawQuery
	} else {
		relativePath = strings.Replace(urlStr, domain, "", -1)
	}

	if param != "" {
		relativePath = strings.Replace(relativePath, param, "", -1)
	}

	//由于 Path 可能不以斜杠开头，我们在这里确保它总是以斜杠开头
	if !strings.HasPrefix(relativePath, "/") {
		relativePath = "/" + relativePath
	}

	return relativePath
}
